# /usr/bin/python
# -*- coding:utf8 -*-
"""
导入火币网trade detail数据
每分钟运行一次
"""
import json

import utils

TABLE_HUOBI_TRADE_DETAIL = 'huobi_trade_data_trade_detail'


class Exchange_data_import:
    def __init__(self, lis_url, table):
        self.u = utils.CoinTools()
        self.conn = self.u.mysqlconnect()
        self.cur = self.conn.cursor()
        self.lis_url = lis_url
        self.table = table

    def run(self):
        lis = []
        for item in self.lis_url:
            data = self.u.doGet(item)
            dic = json.loads(data, encoding='utf8')
            if dic and dic['status'] == 'ok':
                if dic['tick']:
                    i = dic['tick']
                    for d in i['data']:
                        symbol = str(item).split('=')[-1]
                        ts = self.u.secondts_2_mints(long(str(dic['ts'])[:-3]))
                        amount = d['amount']
                        price = d['price']
                        direction = d['direction']
                        lis.append((ts, symbol, amount, price, direction))
        if lis:
            self.insert(lis)

    def insert(self, lis):
        if self.table == TABLE_HUOBI_TRADE_DETAIL:
            sql = """insert into """ + TABLE_HUOBI_TRADE_DETAIL + """ (ts, symbol, amount, price, direction) VALUES (%s,%s,%s,%s,%s)"""
            print sql
            self.cur.executemany(sql, lis)
            self.conn.commit()

    def __del__(self):
        self.conn.commit()
        self.cur.close()
        self.conn.close()


def main():
    tool = utils.CoinTools()
    # 火币网
    lis = ['btc', 'eth', 'bch', 'ltc', 'neo']
    lis_huobi_symbol = ['etcbtc', 'bchbtc', 'ltcbtc', 'neobtc']
    url_huobi_rest_api = tool.readini('exchanges_teade_data', 'URL_HUOBI_REST_API')
    url_huobi_trade_detail = tool.readini('exchanges_teade_data', 'URL_HUIBI_TRADE_DETAIL')
    lis_huobi = []
    for item in lis_huobi_symbol:
        url = url_huobi_rest_api + url_huobi_trade_detail + item
        lis_huobi.append(url)
    if lis_huobi:
        huobi = Exchange_data_import(lis_huobi, TABLE_HUOBI_TRADE_DETAIL)
        huobi.run()


if __name__ == '__main__':
    main()
